<?php
namespace app\index\controller;
use app\index\model\Admin as AdminModel;
use app\index\validate\Admin as AdminValidate;
use think\Session;
use think\Db;
class Admin extends Common
{
  /** 
   * 管理员添加
   */
  public function add()
  {
    if(request()->isAjax()){
      $error = (new AdminValidate())->goCheck();
      if($error !== true){
        $this->error($error);
      }
      $data = input('post.');
      $model = new AdminModel();
      if($model->allowField(true)->save($data)){
        $this->success('添加成功');
      }else{
        $this->error('添加失败');
      }
      return;
    }
    return $this->fetch();
  }

  /**
   * 管理员列表
   */
  public function lst()
  {
    $admin = Db::name('admin')->paginate(20);
    $this->assign('admin',$admin);
    return $this->fetch();
  }

  /**
   * 单条删除
   */
  public function ajax_del(){
    if(request()->isAjax()){
      //接收数据 /d强制转换整型防止sql注入
      $id = input("post.id/d");
      if($id == 1){
        $this->error('不能删除网站所有者');
      }
      $code = AdminModel::destroy($id);
      if($code){
        $this->success('删除成功');
      }else{
        $this->error('删除失败');
      }
      return;
    }
  }

  /**
   * 管理员修改
   */
  public function edit($id)
  {
    $sid = Session::get('id');
    if($sid != $id){
      return $this->error('权限不够');
    }
    $code = db('admin')->find($id);
    if(request()->isAjax()){
      $error = (new AdminValidate())->goCheck();
      if($error !== true){
        return $this->error($error);
      }
      $data = input('post.');
      $admin = new AdminModel();
      $res = $admin->allowField(true)->save($data,['id'=>input('id')]);
      if($res !== false){
        $this->success('修改成功');
      }else{
        $this->error('修改失败');
      } 
      return;
    }
    if(!$code){
      $this->error("该管理员不存在",'lst');
    }
    $this->assign('admin',$code);
    return view();
  }

  /**
   * 清空sessio退出登录
   */
  public function logout(){
    session(null);
    $this->redirect('login/index');
  }
}